<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="MyBatis">
<meta property="og:type" content="article">
<meta property="og:title" content="Java日拱一卒-day21">
<meta property="og:url" content="http://yoursite.com/2020/05/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day21/index.html">
<meta property="og:site_name" content="很惭愧，就做了一点微小的工作">
<meta property="og:description" content="MyBatis">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://yoursite.com/2020/05/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day21/MyBatis.png">
<meta property="article:published_time" content="2020-05-22T04:41:51.000Z">
<meta property="article:modified_time" content="2020-05-29T15:27:32.595Z">
<meta property="article:author" content="文予">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://yoursite.com/2020/05/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day21/MyBatis.png">

<link rel="canonical" href="http://yoursite.com/2020/05/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day21/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Java日拱一卒-day21 | 很惭愧，就做了一点微小的工作</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">很惭愧，就做了一点微小的工作</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">念念不忘，必有回响</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/05/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day21/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/wenyu.png">
      <meta itemprop="name" content="文予">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="很惭愧，就做了一点微小的工作">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java日拱一卒-day21
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-05-22 12:41:51" itemprop="dateCreated datePublished" datetime="2020-05-22T12:41:51+08:00">2020-05-22</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-29 23:27:32" itemprop="dateModified" datetime="2020-05-29T23:27:32+08:00">2020-05-29</time>
              </span>

          
            <div class="post-description">MyBatis</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>MyBatis是一个优秀的持久层框架，对JDBC的操作数据库的过程进行了封装，使得开发者只需要关注SQL本身，不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等JDBC繁杂的过程代码。</p>
<p>MyBatis通过xml或者注解的方式将要执行的各种statement配置起来，并通过java对象和statement中的sql进行映射生成最终执行的SQL语句，最后由MyBatis框架执行SQL并将结果映射成java对象并返回。</p>
<p><img src="/2020/05/22/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day21/MyBatis.png" alt="MyBatis"></p>
<p>(1)mybatis-config.xml是Mybatis的核心配置文件，通过其中的配置可以生成SqlSessionFactory，也就是SqlSession工厂</p>
<p>(2)基于SqlSessionFactory可以生成SqlSession对象</p>
<p>(3)SqlSession是一个既可以发送SQL去执行，并返回结果，类似于JDBC中的Connection对象，也是Mybatis中至关重要的一个对象。</p>
<p>(4)Executor是SqlSession底层的对象，用于执行SQL语句</p>
<p>(5)MapperStatement对象也是SqlSession底层的对象，用于接收输入映射（SQL语句中的参数），以及做输出映射（即将SQL查询的结果映射成相应的结果）</p>
<h2 id="MyBatis快速入门"><a href="#MyBatis快速入门" class="headerlink" title="MyBatis快速入门"></a>MyBatis快速入门</h2><h3 id="准备数据，创建库和表"><a href="#准备数据，创建库和表" class="headerlink" title="准备数据，创建库和表"></a>准备数据，创建库和表</h3><p>准备yonghedb库、emp库</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 1、创建数据库 yonghedb 数据库</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">database</span> <span class="keyword">if</span> <span class="keyword">not</span> <span class="keyword">exists</span> yonghedb <span class="keyword">charset</span> utf8;</span><br><span class="line"><span class="keyword">use</span> yonghedb; <span class="comment">-- 选择yonghedb数据库</span></span><br><span class="line"><span class="comment">-- 2、删除emp表（如果存在）</span></span><br><span class="line"><span class="keyword">drop</span> <span class="keyword">table</span> <span class="keyword">if</span> <span class="keyword">exists</span> emp;</span><br><span class="line"><span class="comment">-- 3、在 yonghedb 库中创建 emp 表</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> emp(</span><br><span class="line">    <span class="keyword">id</span> <span class="built_in">int</span> primary <span class="keyword">key</span> auto_increment,</span><br><span class="line">    <span class="keyword">name</span> <span class="built_in">varchar</span>(<span class="number">50</span>),</span><br><span class="line">    job <span class="built_in">varchar</span>(<span class="number">50</span>),</span><br><span class="line">    salary <span class="keyword">double</span></span><br><span class="line">);</span><br><span class="line"><span class="comment">-- 4、往 emp 表中, 插入若干条记录</span></span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> emp <span class="keyword">values</span>(<span class="literal">null</span>, <span class="string">'关胜'</span>, <span class="string">'大刀'</span>, <span class="number">3300</span>);</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> emp <span class="keyword">values</span>(<span class="literal">null</span>, <span class="string">'林冲'</span>, <span class="string">'豹子头'</span>, <span class="number">2800</span>);</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> emp <span class="keyword">values</span>(<span class="literal">null</span>, <span class="string">'秦明'</span>, <span class="string">'霹雳火'</span>, <span class="number">2700</span>);</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> emp <span class="keyword">values</span>(<span class="literal">null</span>, <span class="string">'呼延灼'</span>, <span class="string">'双鞭'</span>, <span class="number">4200</span>);</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> emp <span class="keyword">values</span>(<span class="literal">null</span>, <span class="string">'董平'</span>, <span class="string">'双枪将'</span>, <span class="number">3000</span>);</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> emp <span class="keyword">values</span>(<span class="literal">null</span>, <span class="string">'宋江'</span>, <span class="string">'呼保义'</span>, <span class="number">3700</span>);</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> emp <span class="keyword">values</span>(<span class="literal">null</span>, <span class="string">'卢俊义'</span>, <span class="string">'玉麒麟'</span>, <span class="number">5000</span>);</span><br></pre></td></tr></table></figure>

<h3 id="创建工程、导入jar包、创建测试类"><a href="#创建工程、导入jar包、创建测试类" class="headerlink" title="创建工程、导入jar包、创建测试类"></a>创建工程、导入jar包、创建测试类</h3><ul>
<li><ol>
<li>创建Maven的测试类</li>
</ol>
</li>
<li><ol start="2">
<li>导入<code>junit</code>、<code>mysql</code>、<code>mybatis</code>、<code>log4j</code>等开发包</li>
</ol>
</li>
</ul>
<p>在<code>pom.xml</code>中引入相关依赖包</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- junit单元测试 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.9<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- mysql驱动 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.1.32<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- mybatis --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.mybatis<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.2.8<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 整合log4j --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.slf4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>slf4j-log4j12<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.6.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li><ol start="3">
<li>创建<code>com.tedu.mybatis.TestMybatis01</code>测试类，提供<code>findAll</code>方法</li>
</ol>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 练习1(快速入门): 查询emp表中的所有员工, 返回一个List&lt;Emp&gt;集合</span></span><br><span class="line"><span class="comment">* <span class="doctag">@throws</span> IOException */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">findAll</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    <span class="comment">//1.读取mybatis的核心配置文件(mybatis-config.xml)</span></span><br><span class="line">    <span class="comment">//2.通过配置信息获取一个SqlSessionFactory工厂对象</span></span><br><span class="line">    <span class="comment">//3.通过工厂获取一个SqlSession对象</span></span><br><span class="line">    <span class="comment">//4.通过namespace+id找到要执行的sql语句并执行sql语句</span></span><br><span class="line">    <span class="comment">//5.输出结果</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="添加mybatis-config-xml文件"><a href="#添加mybatis-config-xml文件" class="headerlink" title="添加mybatis-config.xml文件"></a>添加<code>mybatis-config.xml</code>文件</h3><p>在<code>src/main/resource</code>下，创建<code>mybatis-config.xml</code>文件（MyBatis的核心配置文件）</p>
<p><code>mybatis-config</code>文件头信息如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">configuration</span></span></span><br><span class="line"><span class="meta">    <span class="meta-keyword">PUBLIC</span> <span class="meta-string">"-//mybatis.org//DTD Config 3.0//EN"</span></span></span><br><span class="line"><span class="meta">    <span class="meta-string">"http://mybatis.org/dtd/mybatis-3-config.dtd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- MyBatis的全局配置文件 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">configuration</span> &gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>mybatis-config</code>文件详细配置如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">configuration</span></span></span><br><span class="line"><span class="meta">    <span class="meta-keyword">PUBLIC</span> <span class="meta-string">"-//mybatis.org//DTD Config 3.0//EN"</span></span></span><br><span class="line"><span class="meta">    <span class="meta-string">"http://mybatis.org/dtd/mybatis-3-config.dtd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- MyBatis的全局配置文件 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">configuration</span> &gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 1.配置环境，可配置多个环境（比如：develop开发、test测试） --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">environments</span> <span class="attr">default</span>=<span class="string">"develop"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">environment</span> <span class="attr">id</span>=<span class="string">"develop"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">&lt;!-- 1.1.配置事务管理方式：JDBC/MANAGED</span></span><br><span class="line"><span class="comment">            JDBC：将事务交给JDBC管理（推荐）</span></span><br><span class="line"><span class="comment">            MANAGED：自己管理事务</span></span><br><span class="line"><span class="comment">              --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">transactionManager</span> <span class="attr">type</span>=<span class="string">"JDBC"</span>&gt;</span><span class="tag">&lt;/<span class="name">transactionManager</span>&gt;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">&lt;!-- 1.2.配置数据源，即连接池 JNDI/POOLED/UNPOOLED</span></span><br><span class="line"><span class="comment">                JNDI：已过时</span></span><br><span class="line"><span class="comment">                POOLED：使用连接池（推荐）</span></span><br><span class="line"><span class="comment">                UNPOOLED：不使用连接池</span></span><br><span class="line"><span class="comment">             --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">dataSource</span> <span class="attr">type</span>=<span class="string">"POOLED"</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driver"</span> <span class="attr">value</span>=<span class="string">"com.mysql.jdbc.Driver"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"url"</span> <span class="attr">value</span>=<span class="string">"jdbc:mysql://localhost:3306/yonghedb?characterEncoding=utf-8"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"root"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"root"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">dataSource</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">environment</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">environments</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 2.导入Mapper配置文件，如果mapper文件有多个，可以通过多个mapper标签导入 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mappers</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">mapper</span> <span class="attr">resource</span>=<span class="string">"EmpMapper.xml"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">mappers</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="添加EmpMapper-xml文件"><a href="#添加EmpMapper-xml文件" class="headerlink" title="添加EmpMapper.xml文件"></a>添加<code>EmpMapper.xml</code>文件</h3><p>在src/main/resources目录下，创建EmpMapper.xml文件 （实体类的映射文件）<br>EmpMapper文件头信息如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">mapper</span></span></span><br><span class="line"><span class="meta">    <span class="meta-keyword">PUBLIC</span> <span class="meta-string">"-//mybatis.org//DTD Mapper 3.0//EN"</span></span></span><br><span class="line"><span class="meta">    <span class="meta-string">"http://mybatis.org/dtd/mybatis-3-mapper.dtd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- </span></span><br><span class="line"><span class="comment">    不同Mapper文件的namespace值应该保证唯一</span></span><br><span class="line"><span class="comment">    在程序中通过[ namespace + id ]定位到要执行哪一条SQL语句</span></span><br><span class="line"><span class="comment"> --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">""</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>详细配置如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">mapper</span></span></span><br><span class="line"><span class="meta">    <span class="meta-keyword">PUBLIC</span> <span class="meta-string">"-//mybatis.org//DTD Mapper 3.0//EN"</span></span></span><br><span class="line"><span class="meta">    <span class="meta-string">"http://mybatis.org/dtd/mybatis-3-mapper.dtd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- </span></span><br><span class="line"><span class="comment">    不同Mapper文件的namespace值应该保证唯一</span></span><br><span class="line"><span class="comment">    在程序中通过[ namespace + id ]定位到要执行哪一条SQL语句</span></span><br><span class="line"><span class="comment"> --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">"EmpMapper"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 通过select、insert、update、delete标签声明要执行的SQL --&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 练习1: 查询emp表中的所有员工信息</span></span><br><span class="line"><span class="comment">        resultType指定查询的结果将会封装到什么类型中</span></span><br><span class="line"><span class="comment">        即使最终返回的结果是集合(List&lt;Emp&gt;),resultType也只需要指定集合中的泛型即可!</span></span><br><span class="line"><span class="comment">     --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findAll"</span> <span class="attr">resultType</span>=<span class="string">"com.tedu.pojo.Emp"</span>&gt;</span></span><br><span class="line">        select * from emp</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="添加并编写Emp实体类"><a href="#添加并编写Emp实体类" class="headerlink" title="添加并编写Emp实体类"></a>添加并编写Emp实体类</h3><p>在当前实例中，Emp类中的属性和数据库表的字段名必须一致。</p>
<p>在<code>src/main/java</code>目录下创建<code>com.tedu.pojo.Emp</code>类，并编辑Emp类：提供私有属性以及对应的getter方法、setter方法，并重写toString方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.tedu.pojo;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 实体类,用于封装Emp表中的一条用户信息</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Emp</span> </span>&#123;</span><br><span class="line">    <span class="comment">//1.声明实体类中的属性</span></span><br><span class="line">    <span class="keyword">private</span> Integer id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> String job;</span><br><span class="line">    <span class="keyword">private</span> Double salary;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//2.提供对应的getter和setter方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Integer <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(Integer id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getJob</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> job;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setJob</span><span class="params">(String job)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.job = job;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Double <span class="title">getSalary</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> salary;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setSalary</span><span class="params">(Double salary)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.salary = salary;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//3.重写toString方法</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"Emp [id="</span> + id + <span class="string">", name="</span> + name + <span class="string">", job="</span> + job + <span class="string">", salary="</span> + salary + <span class="string">"]"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="实现测试类并测试"><a href="#实现测试类并测试" class="headerlink" title="实现测试类并测试"></a>实现测试类并测试</h3><p>实现findAll方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 练习1(快速入门):  查询emp表中的所有员工, 返回一个List&lt;Emp&gt;集合</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> IOException */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">findAll</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    <span class="comment">//1.读取mybatis的核心配置文件(mybatis-config.xml)</span></span><br><span class="line">    InputStream in = Resources</span><br><span class="line">            .getResourceAsStream(<span class="string">"mybatis-config.xml"</span>);</span><br><span class="line">    <span class="comment">//2.通过配置信息获取一个SqlSessionFactory工厂对象</span></span><br><span class="line">    SqlSessionFactory fac =</span><br><span class="line">            <span class="keyword">new</span> SqlSessionFactoryBuilder().build( in );</span><br><span class="line">    <span class="comment">//3.通过工厂获取一个SqlSession对象</span></span><br><span class="line">    SqlSession session = fac.openSession();</span><br><span class="line">    <span class="comment">//4.通过namespace+id找到要执行的sql语句并执行sql语句</span></span><br><span class="line">    List&lt;Emp&gt; list = session</span><br><span class="line">            .selectList(<span class="string">"EmpMapper.findAll"</span>);</span><br><span class="line">    <span class="comment">//5.输出结果</span></span><br><span class="line">    <span class="keyword">for</span>(Emp e : list) &#123;</span><br><span class="line">        System.out.println( e );</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行<code>findAll</code>方法，输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Emp [id&#x3D;1, name&#x3D;关胜, job&#x3D;大刀, salary&#x3D;3300.0]</span><br><span class="line">Emp [id&#x3D;2, name&#x3D;林冲, job&#x3D;豹子头, salary&#x3D;2800.0]</span><br><span class="line">Emp [id&#x3D;3, name&#x3D;秦明, job&#x3D;霹雳火, salary&#x3D;2700.0]</span><br><span class="line">Emp [id&#x3D;4, name&#x3D;呼延灼, job&#x3D;双鞭, salary&#x3D;4200.0]</span><br><span class="line">Emp [id&#x3D;5, name&#x3D;董平, job&#x3D;双枪将, salary&#x3D;3000.0]</span><br><span class="line">Emp [id&#x3D;6, name&#x3D;宋江, job&#x3D;呼保义, salary&#x3D;3700.0]</span><br><span class="line">Emp [id&#x3D;7, name&#x3D;卢俊义, job&#x3D;玉麒麟, salary&#x3D;5000.0]</span><br></pre></td></tr></table></figure>

<h2 id="MyBatis入门细节"><a href="#MyBatis入门细节" class="headerlink" title="MyBatis入门细节"></a>MyBatis入门细节</h2><h3 id="mybatis-config-xml配置文件"><a href="#mybatis-config-xml配置文件" class="headerlink" title="mybatis-config.xml配置文件"></a>mybatis-config.xml配置文件</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">configuration</span></span></span><br><span class="line"><span class="meta">    <span class="meta-keyword">PUBLIC</span> <span class="meta-string">"-//mybatis.org//DTD Config 3.0//EN"</span></span></span><br><span class="line"><span class="meta">    <span class="meta-string">"http://mybatis.org/dtd/mybatis-3-config.dtd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- MyBatis的全局配置文件 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">configuration</span> &gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 1.配置环境，可配置多个环境（比如：develop开发、test测试） --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">environments</span> <span class="attr">default</span>=<span class="string">"develop"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">environment</span> <span class="attr">id</span>=<span class="string">"develop"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">&lt;!-- 1.1.配置事务管理方式：JDBC/MANAGED</span></span><br><span class="line"><span class="comment">            JDBC：将事务交给JDBC管理（推荐）</span></span><br><span class="line"><span class="comment">            MANAGED：自己管理事务</span></span><br><span class="line"><span class="comment">              --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">transactionManager</span> <span class="attr">type</span>=<span class="string">"JDBC"</span>&gt;</span><span class="tag">&lt;/<span class="name">transactionManager</span>&gt;</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">&lt;!-- 1.2.配置数据源，即连接池 JNDI/POOLED/UNPOOLED</span></span><br><span class="line"><span class="comment">                JNDI：已过时</span></span><br><span class="line"><span class="comment">                POOLED：使用连接池（推荐）</span></span><br><span class="line"><span class="comment">                UNPOOLED：不使用连接池</span></span><br><span class="line"><span class="comment">             --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">dataSource</span> <span class="attr">type</span>=<span class="string">"POOLED"</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"driver"</span> <span class="attr">value</span>=<span class="string">"com.mysql.jdbc.Driver"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"url"</span> <span class="attr">value</span>=<span class="string">"jdbc:mysql://localhost:3306/yonghedb?characterEncoding=utf-8"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"username"</span> <span class="attr">value</span>=<span class="string">"root"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"root"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">dataSource</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">environment</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">environments</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 2.导入Mapper配置文件，如果mapper文件有多个，可以通过多个mapper标签导入 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mappers</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">mapper</span> <span class="attr">resource</span>=<span class="string">"EmpMapper.xml"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">mappers</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>environments</code>标签：该标签内部可以配置多个environment，即多种环境，每种环境可以做不同配置或连接不同数据库。例如，开发、测试、生产环境可能需要不同的配置，连接的数据库可能也不相同，因此我们可以配置三个environment，分别对应上面三种不同的环境。</p>
<p>environment可以配置多个，但是最终要使用的只能是其中一个.</p>
<p><code>environment</code>标签：内部可以配置多种配置信息，下面介绍事务管理配置和数据源配置。</p>
<p><code>transactionManage</code>标签：事务管理配置，mybatis中有两种事务管理方式，也就是</p>
<blockquote>
<p>type=”[JDBC|MANAGED]</p>
</blockquote>
<h3 id="EmpMapper-xml配置文件"><a href="#EmpMapper-xml配置文件" class="headerlink" title="EmpMapper.xml配置文件"></a>EmpMapper.xml配置文件</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">mapper</span></span></span><br><span class="line"><span class="meta">    <span class="meta-keyword">PUBLIC</span> <span class="meta-string">"-//mybatis.org//DTD Mapper 3.0//EN"</span></span></span><br><span class="line"><span class="meta">    <span class="meta-string">"http://mybatis.org/dtd/mybatis-3-mapper.dtd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- </span></span><br><span class="line"><span class="comment">    不同Mapper文件的namespace值应该保证唯一</span></span><br><span class="line"><span class="comment">    在程序中通过[ namespace + id ]定位到要执行哪一条SQL语句</span></span><br><span class="line"><span class="comment"> --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">"EmpMapper"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 通过select、insert、update、delete标签声明要执行的SQL --&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 练习1: 查询emp表中的所有员工信息</span></span><br><span class="line"><span class="comment">        resultType指定查询的结果将会封装到什么类型中</span></span><br><span class="line"><span class="comment">        即使最终返回的结果是集合(List&lt;Emp&gt;),resultType也只需要指定集合中的泛型即可!</span></span><br><span class="line"><span class="comment">     --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findAll"</span> <span class="attr">resultType</span>=<span class="string">"com.tedu.pojo.Emp"</span>&gt;</span></span><br><span class="line">        select * from emp</span><br><span class="line">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li><p>(1)第1行是xml的文档声明，用于声明xml的版本和编码</p>
</li>
<li><p>(2)第2、3、4行，引入了xml约束文档，当前xml文档将会按照mybatis-3-mapper.dtd文件所要求的规则进行书写。</p>
</li>
<li><p>(3)Mapper标签：根标签，其中namespace(名称空间，也叫命名空间)，要求不能重复。在程序中通过【namespace + id 】定位到要执行哪一条SQL语句</p>
</li>
<li><p>(4)select标签：用于指定将来要执行的各种SQL语句。标签上可以声明属性，下面介绍常用的属性：id、resultType、resultMap</p>
<ul>
<li><p>id属性：要求值不能重复。将来在执行SQL时，可以通过【namespace + id】找到指定SQL并执行。</p>
</li>
<li><p>resultType属性：从这条SQL语句中返回所期望类型的类的完全限定名称（包名+类名）。注意如果是集合情形，那应该是集合可以包含的类型，而不能是集合本身。</p>
<p>简而言之，resultType控制查询SQL执行后返回值的类型或集合中的泛型，例如查询emp表中的单条记录，返回值是一个Emp对象，因此，resultType=”com.tedu.pojo.Emp”；</p>
<p> 如果查询emp表中的多条记录，返回值是一个List&lt;Emp&gt;，此时resultType的值应该集合中的泛型，因此resultType=”com.tedu.pojo.Emp”；</p>
</li>
<li><p>resultMap属性：复杂对象结构（例如多表关联查询等）。 使用 resultType 或 resultMap，但不能同时使用。</p>
</li>
</ul>
</li>
</ul>
<h2 id="MyBatis增删改查"><a href="#MyBatis增删改查" class="headerlink" title="MyBatis增删改查"></a>MyBatis增删改查</h2><h3 id="新增员工"><a href="#新增员工" class="headerlink" title="新增员工"></a>新增员工</h3><ul>
<li>1.编辑EmpMapper.xml文件, 添加新增员工对应的sql</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 练习2: 新增员工信息: 石秀 拼命三郎 6000</span></span><br><span class="line"><span class="comment">增删改的标签上不用指定resultType, 因为返回值都是int类型</span></span><br><span class="line"><span class="comment">--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"insert"</span> &gt;</span></span><br><span class="line">    insert into emp value(null, '石秀', '拼命三郎', 6000)</span><br><span class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li><ol start="2">
<li>编写TestMybatis类，添加testInsert方法，实现新增员工操作</li>
</ol>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 练习2: 新增员工信息: 石秀 拼命三郎 6000 */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testInsert</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="comment">//执行sql语句, 返回执行结果</span></span><br><span class="line">  <span class="keyword">int</span> rows = session.update(<span class="string">"EmpMapper.insert"</span>);</span><br><span class="line">  <span class="comment">//提交事务</span></span><br><span class="line">  session.commit();</span><br><span class="line">  System.out.println(<span class="string">"影响的行数: "</span>+rows);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="修改员工"><a href="#修改员工" class="headerlink" title="修改员工"></a>修改员工</h3><ul>
<li><ol>
<li>编辑EmpMapper.xml文件, 添加新增员工对应的sql</li>
</ol>
</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 练习3：修改员工信息：赵云 保镖 20000 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"update"</span>&gt;</span></span><br><span class="line">    update emp set job='保镖', salary=20000 where name='赵云'</span><br><span class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>2.编写TestMybatis类，添加testUpdate方法，实现修改员工信息</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 练习3: 修改员工信息, 将赵云的job改为'保镖'，salary改为20000 */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testUpdate</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="comment">//执行sql语句, 返回执行结果</span></span><br><span class="line">  <span class="keyword">int</span> rows = session.update(<span class="string">"EmpMapper.update"</span>);</span><br><span class="line">  <span class="comment">//提交事务</span></span><br><span class="line">  session.commit();</span><br><span class="line">  System.out.println(<span class="string">"影响行数:"</span>+rows);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="删除员工"><a href="#删除员工" class="headerlink" title="删除员工"></a>删除员工</h3><ul>
<li><ol>
<li>编辑EmpMapper.xml文件, 添加删除员工对应的sql</li>
</ol>
</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 练习4: 删除name为'石秀'的记录 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"delete"</span>&gt;</span></span><br><span class="line">    delete from emp where name='石秀'</span><br><span class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li><ol start="2">
<li>编写TestMybatis类，添加<strong>testDelete</strong>方法，实现删除员工</li>
</ol>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 练习4: 删除name为'石秀'的记录 */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testDelete</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="comment">//执行sql语句, 返回执行结果</span></span><br><span class="line">  <span class="keyword">int</span> rows = session.update(<span class="string">"EmpMapper.delete"</span>);</span><br><span class="line">  <span class="comment">//提交事务</span></span><br><span class="line">  session.commit();</span><br><span class="line">  System.out.println(<span class="string">"影响行数:"</span>+rows);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="MyBatis的占位符"><a href="#MyBatis的占位符" class="headerlink" title="MyBatis的占位符"></a>MyBatis的占位符</h2><h3 id="占位符"><a href="#占位符" class="headerlink" title="#{}占位符"></a><code>#{}</code>占位符</h3><p>相当于JDBC中的问号<code>?</code>占位符,是为SQL语句中的参数值进行占位,大部分情况下都是使用<code>#{}</code>占位符; 并且当<code>#{}</code>占位符是为字符串或者日期类型的值进行占位时,在参数值传过来替换占位符的同时,会进行转义处理(在字符串或日期类型的值的两边加上单引号)</p>
<p>练习5：查询emp表中指定id的员工信息</p>
<p>在mapper文件中编写SQL语句：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 练习5: 查询emp表中指定id的员工信息 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findById"</span> <span class="attr">resultType</span>=<span class="string">"com.tedu.pojo.Emp"</span>&gt;</span></span><br><span class="line">    select * from emp where id=#&#123;id&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>java代码实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 练习5: 查询emp表中指定id的员工信息 */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testFindById</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="comment">//执行sql语句, 返回执行结果</span></span><br><span class="line">  Emp emp = session.selectOne( <span class="string">"EmpMapper.findById"</span>, <span class="number">1</span> );</span><br><span class="line">  System.out.println( emp );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>练习6：新增员工信息: 武松 行者 15000</p>
<p>在mapper文件中编写SQL语句：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 练习6: 新增员工信息: 武松 行者 15000</span></span><br><span class="line"><span class="comment">  如果通过map集合传输参数, 需要保证占位符中的变量名</span></span><br><span class="line"><span class="comment">  和map集合中的key保持一致</span></span><br><span class="line"><span class="comment">  如果通过pojo对象传输参数, 需要保证占位符中的变量名</span></span><br><span class="line"><span class="comment">  和对象中的属性名保持一致, 或者在pojo中有对应的</span></span><br><span class="line"><span class="comment">  getXxx方法</span></span><br><span class="line"><span class="comment">--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"insert2"</span>&gt;</span></span><br><span class="line">    insert into emp values (null, #&#123;name&#125;, #&#123;job&#125;, #&#123;salary&#125;)</span><br><span class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>java代码实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 练习6: 新增员工信息: 武松 行者 15000 */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testInsert2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="comment">//将要传输的参数封装到map集合中</span></span><br><span class="line">  <span class="comment">//Map map = new HashMap();</span></span><br><span class="line">  <span class="comment">//map.put("name", "武松");</span></span><br><span class="line">  <span class="comment">//map.put("job", "行者");</span></span><br><span class="line">  <span class="comment">//map.put("salary", 15000);</span></span><br><span class="line">  <span class="comment">//也可以将要传输的参数封装到Emp对象中</span></span><br><span class="line">  Emp emp = <span class="keyword">new</span> Emp();</span><br><span class="line">  emp.setName(<span class="string">"武松"</span>);</span><br><span class="line">  emp.setJob(<span class="string">"行者"</span>);</span><br><span class="line">  emp.setSalary(<span class="number">15000.0</span>);</span><br><span class="line">  <span class="comment">//执行sql语句</span></span><br><span class="line">  intsession rows = session.update(<span class="string">"EmpMapper.insert2"</span>, emp);</span><br><span class="line">  <span class="comment">//提交事务</span></span><br><span class="line">  session.commit();</span><br><span class="line">  System.out.println( <span class="string">"影响的行数: "</span>+rows );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的练习中，当SQL语句中包含的参数值是传递过来的，在SQL语句中我们会通过<code>#{}</code>占位符进行占位，在SQL语句真正执行时，再将传递过来的值替换SQL语句中的占位符。</p>
<p>其实，<code>#{}</code>就是JDBC中的问号<code>?</code>占位符，因此为了安全考虑，在执行时会对传递过来的字符串和日期类型高的值进行转译处理。</p>
<p>例如：查询指定name的员工信息，SQL语句为：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> emp <span class="keyword">where</span> <span class="keyword">name</span>=<span class="comment">#&#123;name&#125;</span></span><br></pre></td></tr></table></figure>

<p>其实就等价于JDBC中： <code>select * from emp where name=?</code>，</p>
<p>如果传过来的参数值为：宋江，那么最终执行的SQL语句为：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 在参数替换占位符的同时进行了转义处理(在值的两边加上了单引号)</span></span><br><span class="line"><span class="keyword">select</span> * <span class="keyword">from</span> emp <span class="keyword">where</span> <span class="keyword">name</span>=<span class="string">'宋江'</span></span><br></pre></td></tr></table></figure>

<h3 id="占位符-1"><a href="#占位符-1" class="headerlink" title="${}占位符"></a><code>${}</code>占位符</h3><p><code>${}</code>用于传递一个SQL片段，例如：在查询时，我们想动态的传递查询的列：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> <span class="comment">#&#123;columns&#125; from emp</span></span><br></pre></td></tr></table></figure>

<p>此时传递过来的应该是一个SQL片段，不同于上面的参数值，如果此时还用<code>#{}</code>，也会像上面一样被转译处理：<code>select &#39;id,name,job&#39; from emp</code></p>
<p>如果不想让传过来的SQL片段被转译处理，而是直接拼接在SQL语句中，那么这里可以使用<code>${}</code>，例如：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> $&#123;<span class="keyword">columns</span>&#125; <span class="keyword">from</span> emp</span><br></pre></td></tr></table></figure>

<p>拼接之后：<code>select id,name,job from emp</code></p>
<p>练习9：动态指定要查询的列</p>
<p>在mapper文件中编写SQL语句：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 练习9: 动态指定要查询的列 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findAll2"</span> <span class="attr">resultType</span>=<span class="string">"com.tedu.pojo.Emp"</span>&gt;</span></span><br><span class="line">    select $&#123;cols&#125; from emp</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>java代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** 练习9: 动态指定要查询的列 */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testFindAll2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  Map map = <span class="keyword">new</span> HashMap();</span><br><span class="line">  <span class="comment">//map.put("cols", "id, name");</span></span><br><span class="line">  <span class="comment">//map.put("cols", "id, name, salary");</span></span><br><span class="line">  map.put(<span class="string">"cols"</span>, <span class="string">"id,name,job,salary"</span>);</span><br><span class="line">  <span class="comment">//执行sql语句, 返回结果</span></span><br><span class="line">  List&lt;Emp&gt; list = session.selectList(<span class="string">"EmpMapper.findAll2"</span>, map);</span><br><span class="line">  <span class="comment">//输出结果</span></span><br><span class="line">  <span class="keyword">for</span> ( Emp e : list ) &#123;</span><br><span class="line">    System.out.println( e );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="动态SQL标签"><a href="#动态SQL标签" class="headerlink" title="动态SQL标签"></a>动态SQL标签</h2><h3 id="if、where标签"><a href="#if、where标签" class="headerlink" title="if、where标签"></a>if、where标签</h3><ul>
<li><p><code>&lt;if&gt;</code>标签：是根据<code>test属性</code>中的布尔表达式的值，从而决定是否执行包含在其中的SQL片段。如果判断结果为true，则执行其中的SQL片段；如果结果为false，则不执行其中的SQL片段</p>
</li>
<li><p><code>&lt;where&gt;</code>标签：用于对包含在其中的SQL片段进行检索，在需要时可以生成where关键字，并且在需要时会剔除多余的连接词（比如and或者or）</p>
</li>
</ul>
<p>练习12：根据薪资查询员工信息（if标签）</p>
<ul>
<li><code>&lt;if&gt;</code>标签：是根据<code>test属性</code>中的布尔表达式的值，从而决定是否执行包含在其中的SQL片段。如果判断结果为true，则执行其中的SQL片段；如果结果为false，则不执行其中的SQL片段</li>
</ul>
<p>在mapper文件中编写SQL语句：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 练习12: 根据薪资查询员工信息</span></span><br><span class="line"><span class="comment">* 如果没有参数, 则不执行where子句, 默认查询所有员工：</span></span><br><span class="line"><span class="comment">*     select * from emp</span></span><br><span class="line"><span class="comment">* 如果参数中只有minSal(即minSal不为null), 则：</span></span><br><span class="line"><span class="comment">*     ... where salary &gt; minSal</span></span><br><span class="line"><span class="comment">* 如果参数中只有maxSal(即maxSal不为null), 则：</span></span><br><span class="line"><span class="comment">*     ... where salary &lt; maxSal</span></span><br><span class="line"><span class="comment">* 如果参数有 minSal、maxSal(即minSal、maxSal不为null), 则：</span></span><br><span class="line"><span class="comment">*        ... where salary &gt; minSal and salary &lt; maxSal  --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findAllBySal"</span> <span class="attr">resultType</span>=<span class="string">"com.tedu.pojo.Emp"</span>&gt;</span></span><br><span class="line">  select * from emp</span><br><span class="line">  where 1=1</span><br><span class="line">  <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"minSal != null"</span>&gt;</span></span><br><span class="line">      and salary&gt;#&#123;minSal&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">"maxSal != null"</span>&gt;</span></span><br><span class="line">      and salary &lt;![CDATA[ &lt; ]]&gt; #&#123;maxSal&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Java代码实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 练习12: 根据薪资查询员工信息</span></span><br><span class="line"><span class="comment">* 如果没有参数, 则不执行where子句, 默认查询所有员工：</span></span><br><span class="line"><span class="comment">*     select * from emp</span></span><br><span class="line"><span class="comment">* 如果参数中只有minSal(即minSal不为null), 则：</span></span><br><span class="line"><span class="comment">*     ... where salary &gt; minSal</span></span><br><span class="line"><span class="comment">* 如果参数中只有maxSal(即maxSal不为null), 则：</span></span><br><span class="line"><span class="comment">*     ... where salary &lt; maxSal</span></span><br><span class="line"><span class="comment">* 如果参数有 minSal、maxSal(即minSal、maxSal不为null), 则：</span></span><br><span class="line"><span class="comment">*    ... where salary &gt; minSal and salary &lt; maxSal  */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testFindBySal</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Map&lt;String, Object&gt; map = <span class="keyword">new</span> HashMap&lt;String, Object&gt;();</span><br><span class="line">    <span class="comment">//map.put( "minSal" , 3000 );</span></span><br><span class="line">    <span class="comment">//map.put( "maxSal", 4000 );</span></span><br><span class="line">    List&lt;Emp&gt; list = session.selectList( <span class="string">"EmpMapper.findBySal"</span>, map );</span><br><span class="line">    <span class="keyword">for</span> (Emp emp : list) &#123;</span><br><span class="line">        System.out.println( emp );</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="foreach元素"><a href="#foreach元素" class="headerlink" title="foreach元素"></a>foreach元素</h3><p>foreach标签：可以对传过来的参数数组或集合进行遍历，以下是foreach标签上的各个属性介绍：</p>
<table>
<thead>
<tr>
<th align="center">属性</th>
<th align="center">属性描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">collection</td>
<td align="center">必需，值为遍历的集合类型，例如：如果参数只是一个数组或List集合，则collection的值为array或list；如果传的是多个参数，用map封装，collection则指定为map中的key。</td>
</tr>
<tr>
<td align="center">item</td>
<td align="center">必需，若collection为数组或List集合时，item表示其中的元素，若collection为map中的key，item表示map中value（集合或数组）中的元素</td>
</tr>
<tr>
<td align="center">open</td>
<td align="center">可选，表示遍历生成的SQL片段以什么开始，最常用的是左括号’(‘</td>
</tr>
<tr>
<td align="center">close</td>
<td align="center">可选，表示遍历生成的SQL片段以什么结束，最常用的是右括号’)’</td>
</tr>
<tr>
<td align="center">separator</td>
<td align="center">可选，每次遍历后给生成的SQL片段后面指定间隔符</td>
</tr>
</tbody></table>
<p>练习14: 根据员工的id批量删除员工信息</p>
<p>在mapper文件中编写SQL语句：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 练习14: 根据员工的id批量删除员工信息</span></span><br><span class="line"><span class="comment">    delete from emp where id in (1,3,5,7)</span></span><br><span class="line"><span class="comment">    collection: 如果传的参数仅仅是一个数组或者List集合, collection可以指定为</span></span><br><span class="line"><span class="comment">        array或list; 如果传的是多个参数，用map封装，collection则指定为map中的key</span></span><br><span class="line"><span class="comment">    open: 指定生成的SQL片段以什么符号开始</span></span><br><span class="line"><span class="comment">    close: 指定生成的SQL片段以什么符号结束</span></span><br><span class="line"><span class="comment">    item: 指定变量接收数组或集合中的元素</span></span><br><span class="line"><span class="comment">    separator: 指定一个间隔符, 在将数组或集合中的每个元素拼接到SQL片段之后, </span></span><br><span class="line"><span class="comment">        在后面拼接一个间隔符</span></span><br><span class="line"><span class="comment"> --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">delete</span> <span class="attr">id</span>=<span class="string">"deleteByIds"</span>&gt;</span></span><br><span class="line">    delete from emp where id in</span><br><span class="line">    <span class="tag">&lt;<span class="name">foreach</span> <span class="attr">collection</span>=<span class="string">"array"</span> <span class="attr">open</span>=<span class="string">"("</span> <span class="attr">item</span>=<span class="string">"id"</span> <span class="attr">separator</span>=<span class="string">","</span> <span class="attr">close</span>=<span class="string">")"</span>&gt;</span></span><br><span class="line">        #&#123;id&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">foreach</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">delete</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>Java代码实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 练习14: 根据员工的id批量删除员工信息 */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testDeleteByIds</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获取所要删除的员工的id数组</span></span><br><span class="line">    Integer[] ids = &#123;<span class="number">1</span>,<span class="number">3</span>,<span class="number">5</span>,<span class="number">7</span>&#125;;</span><br><span class="line">    <span class="keyword">int</span> rows = session.delete( <span class="string">"EmpMapper.deleteByIds"</span>, ids );</span><br><span class="line">    System.out.println( <span class="string">"影响行数: "</span>+rows );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/05/20/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day20/" rel="prev" title="Java日拱一卒-day20">
      <i class="fa fa-chevron-left"></i> Java日拱一卒-day20
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/05/30/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day22/" rel="next" title="Java日拱一卒-day22">
      Java日拱一卒-day22 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#MyBatis快速入门"><span class="nav-number">1.</span> <span class="nav-text">MyBatis快速入门</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#准备数据，创建库和表"><span class="nav-number">1.1.</span> <span class="nav-text">准备数据，创建库和表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建工程、导入jar包、创建测试类"><span class="nav-number">1.2.</span> <span class="nav-text">创建工程、导入jar包、创建测试类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加mybatis-config-xml文件"><span class="nav-number">1.3.</span> <span class="nav-text">添加mybatis-config.xml文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加EmpMapper-xml文件"><span class="nav-number">1.4.</span> <span class="nav-text">添加EmpMapper.xml文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加并编写Emp实体类"><span class="nav-number">1.5.</span> <span class="nav-text">添加并编写Emp实体类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实现测试类并测试"><span class="nav-number">1.6.</span> <span class="nav-text">实现测试类并测试</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MyBatis入门细节"><span class="nav-number">2.</span> <span class="nav-text">MyBatis入门细节</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#mybatis-config-xml配置文件"><span class="nav-number">2.1.</span> <span class="nav-text">mybatis-config.xml配置文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#EmpMapper-xml配置文件"><span class="nav-number">2.2.</span> <span class="nav-text">EmpMapper.xml配置文件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MyBatis增删改查"><span class="nav-number">3.</span> <span class="nav-text">MyBatis增删改查</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#新增员工"><span class="nav-number">3.1.</span> <span class="nav-text">新增员工</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#修改员工"><span class="nav-number">3.2.</span> <span class="nav-text">修改员工</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除员工"><span class="nav-number">3.3.</span> <span class="nav-text">删除员工</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MyBatis的占位符"><span class="nav-number">4.</span> <span class="nav-text">MyBatis的占位符</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#占位符"><span class="nav-number">4.1.</span> <span class="nav-text">#{}占位符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#占位符-1"><span class="nav-number">4.2.</span> <span class="nav-text">${}占位符</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#动态SQL标签"><span class="nav-number">5.</span> <span class="nav-text">动态SQL标签</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#if、where标签"><span class="nav-number">5.1.</span> <span class="nav-text">if、where标签</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#foreach元素"><span class="nav-number">5.2.</span> <span class="nav-text">foreach元素</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="文予"
      src="/uploads/wenyu.png">
  <p class="site-author-name" itemprop="name">文予</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">29</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文予</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>


        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

</body>
</html>
